﻿using System;
using System.Drawing;
using System.Windows.Forms;
using DoMain.SetDomain;

namespace TMIS.SetForms
{
    public partial class UserSetForm : Form
    {
        readonly UserSetDomain _userSetDomain = new UserSetDomain();

        public UserSetForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 表格数据查询
        /// </summary>
        private void GridDataQuery()
        {
            var dataSet = _userSetDomain.UserQuery();
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = dataSet;
        }

        /// <summary>
        /// 角色名查询
        /// </summary>
        private void RoleNameQuery()
        {
            var result = _userSetDomain.RoleQuery();
            if (result == null)
            {
                comboBox_role.Items.Clear();
            }
            else
            {
                foreach (var role in result)
                {
                    comboBox_role.Items.Add(role);
                }

                comboBox_role.SelectedIndex = 0;
            }
        }

        private void UserSetForm_Load(object sender, EventArgs e)
        {
            GridDataQuery();
            RoleNameQuery();
        }

        private void button_addUser_Click(object sender, EventArgs e)
        {
            string userName = textBox_userName.Text;
            string roleName = comboBox_role.Text;
            var image = pictureBox1.Image;
            if (image == null)
            {
                MessageBox.Show(@"电子签名为空，请检查。");
            }
            else if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(roleName))
            {
                MessageBox.Show(@"输入的用户名或角色为空，请检查。");
            }
            else if (userName.Length >= 255)
            {
                MessageBox.Show(@"用户名输入不符合格式，请检查。");
            }
            else if (_userSetDomain.IsNameExist(userName))
            {
                MessageBox.Show(@"用户名已存在，请检查。");
            }
            else
            {
                Image.FromFile(openFileDialog1.FileName).Dispose();
                _userSetDomain.AddUser(userName, roleName, openFileDialog1.FileName);
            }

            GridDataQuery();
        }

        private void button_openFile_Click(object sender, EventArgs e)
        {
            try
            {
                openFileDialog1.ShowDialog();
                string fileName = openFileDialog1.FileName; //实际输出的是文件的完整路径
                pictureBox1.Image = string.IsNullOrEmpty(fileName) ? null : Image.FromFile(fileName);
            }
            catch (Exception)
            {
                // ignored
            }
        }
    }
}